<template>
	<view class="page_content">
		<!-- <view class="page-bgc">
		</view> -->
		<view class="head_content">
			<view class="navbar">盼盼短剧</view>
		</view>
		<view class="main_content">
			<view class="content_box">
				<view class="tabs">
					<view class="itemList">
						<!-- 分类列表 -->
						<view class="items" :class="{ active: isSelected(tabItem) }"
							v-for="(tabItem, tabIndex) in tabsList" :key="tabIndex" @click="changeTabs(tabItem)">
							{{ tabItem.classifyName || '分类'}}
						</view>
					</view>
					<view class="icon" @click="opShow">
						<u-icon name="arrow-down" color="#000" size="14"></u-icon>
					</view>
					<view class="backls" v-if="show">
					</view>
				</view>
				<scroll-view style="height: 100%;" :scroll-y="true" :refresher-enabled="true" :refresher-threshold="100"
					:refresher-triggered="refreshStatus" @refresherrefresh="refreshHandle" @scrolltolower="bottomHandle"
					@scroll="scrollHandle">
					<uv-swiper showTitle keyName="image" height="160" :list="list" indicator interval="4000"
						indicatorMode="line" circular indicatorActiveColor="#fff" radius="10"
						:title-style="{color:'#fff',textAlign: 'left',paddingLeft:'20rpx'}"></uv-swiper>
					<view class="list" v-if="videoList.length > 0">
						<block v-for="(lItems, lIndex) in videoList" :key="lItems.id">
							<view class="item item1" @click="openVideoDetail(lItems)">
								<view class="img">
									<image class="image" :src="lItems.dramaPoster" mode="aspectFill"></image>
									<view class="count">
										<u-icon name="play-right-fill" color="#fff" size="14"></u-icon>
										{{lItems.totalPlay || 0}}
									</view>
								</view>
								<view class="info">
									<view class="title u-line-1">{{ lItems.dramaName }}</view>
									<view class="text u-line-1">{{lItems.classifyName}} · {{ lItems.totalEpisodes}}集
									</view>
								</view>
							</view>
						</block>
					</view>
					<view class="nodata" v-else>
						<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" />
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="opBox" v-if="show">
			<view class="opTitle">
				<view class="text">筛选</view>
				<view class="close" @click="close">
					<u-icon name="close" color="#000" size="18"></u-icon>
				</view>
			</view>
			<view class="opContent">
				<view class="boxT">
					<view class="t-title">频道</view>
					<view class="t-content">
						<view class="t-item" :class="{ active: tabItem.id === selectedTabId}"
							v-for="(tabItem, tabIndex) in channel" :key="tabIndex"
							@click="choiceTabs(tabIndex,tabItem)">{{ tabItem.name }}</view>
					</view>
				</view>
				<view class="boxB">
					<view class="b-title">分类</view>
					<view class="b-content">
						<view class="b-item" :class="{ active: isSelected(tabItem) }"
							v-for="(tabItem, tabIndex) in tabsList" :key="tabIndex" @click="changeTabs(tabItem)">
							{{ tabItem.classifyName }}
						</view>
					</view>
				</view>
				<view class="btnBox">
					<view class="reset" @click="reset">重置</view>
					<view class="confirm" @click="confirm">确认</view>
				</view>
			</view>
		</view>
		<TabBar v-if="tabstatus" :tabIndex="0"></TabBar>
	</view>
</template>

<script>
	import apiMoen from '../../utils/config.js';
	import TabBar from '../../components/tabbar/tabbar.vue';
	const PlayerManager = require("../../utils/playerManager.js");
	const playletPlugin = requirePlugin("playlet-plugin");
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from "vuex"
	export default {
		components: {
			TabBar
		},
		data() {
			return {
				tabstatus: false,
				tabIndex: 0,
				list: [{
						image: 'https://baixoss.oss-cn-shenzhen.aliyuncs.com/wxbanner/3.jpg',
						// title: '打工人走上人生巅峰是什么体验',
					},
					{
						image: 'https://baixoss.oss-cn-shenzhen.aliyuncs.com/wxbanner/2.jpg',
						// title: '灰姑娘一路逆袭成长记',
					},
					{
						image: 'https://baixoss.oss-cn-shenzhen.aliyuncs.com/wxbanner/1.jpg',
						// title: '穿越宫廷，卷入皇室争斗如何脱险',
					},
				],
				bindMemberId: null, //上级会员id
				taskId: null, //任务id
				dramaId:null,//剧目ID
				refreshStatus: true,
				// 频道筛选状态
				selectedTabId: "",
				// 集数筛选状态
				episodeId: "",
				videoQuery: {
					tenantId: apiMoen.tenantId,
					sysOrgCode: apiMoen.sysOrgCode,
					dramaClassify: "", //短剧分类
					dramaChannel: "", //频道分类
				},
				show: false,
				navbarTitle: this.$store.state.app.title || '推荐',
				tabsActiveStyle: {
					color: '#EE7F33',
					fontSize: '32rpx',
					fontWeight: 'bold',
				},
				tabsInactiveStyle: {
					color: '#666666'
				},
				contentCurrent: 0,
				refreshStatus: true,
				isRefresh: false,
				tabsList: [{
						id: 1,
						name: '推荐',
						type: 'recommend'
					},
					{
						id: 2,
						name: '分类',
						type: 'new'
					},
					{
						id: 3,
						name: '热门',
						type: 'hot'
					}
				],
				channel: [{
						id: 1,
						name: '男频',
						type: false
					},
					{
						id: 2,
						name: '女频',
						type: false
					},
				],
				episodes: [{
						id: 1,
						totalEpisodesEnd: 1,
						totalEpisodesStart: 30,
						name: '1-30级',
						type: false
					},
					{
						id: 2,
						totalEpisodesEnd: 31,
						totalEpisodesStart: null,
						name: '30集以上',
						type: false
					},
					{
						id: 3,
						totalEpisodesEnd: 61,
						totalEpisodesStart: null,
						name: '60集以上',
						type: false
					},
				],
				classification: [{
						id: 1,
						name: '推荐',
						type: false
					},
					{
						id: 2,
						name: '最新',
						type: false
					},
				],
				tabsActive: {},
				isTabsFixed: false,
				videoList: []
			}
		},
		computed: {
			...mapGetters("user", ["token", "userInfo"]),
			...mapGetters("app", ["title"]),
		},
		watch: {
			title(newValue, oldValue) {
				this.navbarTitle = newValue
			}
		},
		onLoad(options) {
			// this.bindMemberId = options.memberId
			// this.taskId = options.id
			// 使用示例
			console.log("获取 options 参数:", options); // 获取 options 参数
			if (options.q) {
				var url = decodeURIComponent(options.q)
				console.log(url, '数据网络')
				this.bindMemberId = this.getQueryParam(url, 'memberId');
				this.taskId = this.getQueryParam(url, 'id');
				this.dramaId = this.getQueryParam(url, 'dramaId')
				console.log("获取 id 参数:", this.taskId); // 获取 id 参数
				console.log("获取 dramaId 参数:", this.dramaId); // 获取 id 参数
				console.log("获取 memberId 参数", this.bindMemberId); // 获取 memberId 参数
			}
			// var amon = "https%3A%2F%2Fwww.bxduanju.com%3Fid%3D1817925578915618817%26memberId%3D1803069038668271618"
			// let url = decodeURIComponent(amon)
			// console.log(url,'数据网络')
			// var url = 'https://www.example.com/?key=5&foo=6';
			// var paramValue = this.getQueryParam(url, 'key'); // 获取'key'参数的值
			// console.log(paramValue,'paramValue'); // 输出: value
			
			const memberId = uni.getStorageSync('id')
			if (!memberId) {
				this.login()
			}
			this.getVideoClassify()
			setTimeout(() => {
				this.BindPublicizeRecordBind();
			}, 2000); // 2000 毫秒即 2 秒
		},
		onShow() {
			this.getVideoList()
			uni.hideTabBar()
		},
		methods: {
			getQueryParam(url, param) {
				url = url.split('#')[0]; // 去除URL中的hash部分
				var query = url.split('?')[1] || ''; // 获取URL中的查询字符串
				var vars = query.split('&'); // 将查询字符串分割成单个参数
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split('='); // 分割出键和值
					if (pair[0] === param) { // 若找到匹配的参数名称
						return decodeURIComponent(pair[1] || ''); // 返回解码后的参数值
					}
				}
				return null; // 若未找到，返回null
			},
			// wx登录
			login() {
				console.log(apiMoen, 'apiMoen')
				//this指向问题
				const mythis = this
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						// console.log('获取小程序初始化基本信息code222222222222222222')
						console.log('获取小程序初始化基本信息code', code)
						console.log('获取小程序初始化基本信息event', event)
						mythis.$request('login.wxmpLogin', {
							code: code,
							appId: apiMoen.appId, //盼盼短剧
							// appId: 'wxd5208bc6883761bd',//迅捷剧场
						}).then(res => {
							console.log('获取小程序初始化基本信息我进到这儿了', res)
							if (res.code == 200) {
								//目前只是这样简单写
								// console.log('获取小程序初始化基本信息获取成功',res)
								const id = res.result.id
								const tenantId = res.result.tenantId
								const memberName = res.result.memberName
								const sysOrgCode = res.result.sysOrgCode
								const srcAppid = apiMoen.srcAppid //盼盼短剧
								const platform = uni.getSystemInfoSync().platform;
								uni.setStorageSync('platform', platform)
								// const srcAppid = 'wxd5208bc6883761bd'//迅捷剧场
								uni.setStorageSync('id', id)
								uni.setStorageSync('srcAppid', srcAppid)
								uni.setStorageSync('tenantId', tenantId)
								uni.setStorageSync('sysOrgCode', sysOrgCode)
								mythis.getVideoClassify()
							}
						})
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
					}
				})
			},
			// 获取设备信息
			getemInfo() {
				// wx登录
				// login() {
					console.log(apiMoen, 'apiMoen')
					//this指向问题
					const mythis = this
					uni.login({
						"provider": "weixin",
						"onlyAuthorize": true, // 微信登录仅请求授权认证
						success: function(event) {
							const {
								code
							} = event
							// console.log('获取小程序初始化基本信息code222222222222222222')
							console.log('获取小程序初始化基本信息code', code)
							console.log('获取小程序初始化基本信息event', event)
							mythis.$request('login.wxmpLogin', {
								code: code,
								appId: apiMoen.appId, //盼盼短剧
								// appId: 'wxd5208bc6883761bd',//迅捷剧场
							}).then(res => {
								console.log('获取小程序初始化基本信息我进到这儿了', res)
								if (res.code == 200) {
									//目前只是这样简单写
									// console.log('获取小程序初始化基本信息获取成功',res)
									const id = res.result.id
									const tenantId = res.result.tenantId
									const memberName = res.result.memberName
									const sysOrgCode = res.result.sysOrgCode
									const srcAppid = apiMoen.srcAppid //盼盼短剧
									const platform = uni.getSystemInfoSync().platform;
									uni.setStorageSync('platform', platform)
									// const srcAppid = 'wxd5208bc6883761bd'//迅捷剧场
									uni.setStorageSync('id', id)
									uni.setStorageSync('srcAppid', srcAppid)
									uni.setStorageSync('tenantId', tenantId)
									uni.setStorageSync('sysOrgCode', sysOrgCode)
								}
							})
						},
						fail: function(err) {
							// 登录授权失败
							// err.code是错误码
						}
					})
				// },
			},
			// 绑定分销会员
			BindPublicizeRecordBind() {
				if (this.bindMemberId != null || this.taskId != null) {
					var data = {
						bindMemberId: this.bindMemberId,
						taskId: this.taskId,
						sysOrgCode: uni.getStorageSync('sysOrgCode'),
						memberId: uni.getStorageSync('id')
					}
					this.$request('cpsdist.publicizeRecordBind', data).then(res => {
						if (res.code != 200 && res.message != "") {
							uni.showToast({
								title: res.message,
								icon: 'error',
								duration: 2000,
								position: 'center'
							});
						} else {
							uni.showToast({
								title: res.message,
								icon: 'success',
								duration: 2000,
								position: 'center'
							});
							if(this.dramaId){
								this.openVideoCps()
							}
						}
						console.log('绑定分销会员:', res);
					})
				}
			},
			// 绑定分销跳转详情
			openVideoCps() {
				PlayerManager.navigateToPlayer({
					srcAppid: uni.getStorageSync('srcAppid'),
					dramaId: this.dramaId,
				})
			},
			// 获取视频分类
			getVideoClassify() {
				this.$request('video.classify', {
					sysOrgCode: apiMoen.sysOrgCode
				}).then(res => {
					if (res.code !== 200) {
						uni.showToast({
							title: '获取视频分类失败',
							icon: 'none',
							duration: 2000 // 提示框显示时长
						});
					}
					this.tabsList = res.result
					// console.log("this.tabsList", that.tabsList);
					// console.log("res视频分类:", res);
				})
			},
			// 获取视频列表
			getVideoList() {
				this.$request('video.filmDramaList', this.videoQuery).then(res => {
					// console.log("视频列表:", res);
					if (res.code != 200) {
						uni.showToast({
							title: '视频列表获取失败',
							icon: 'none',
							duration: 2000 // 提示框显示时长
						});
					}
					this.videoList = res.result
					this.tabstatus = true
					console.log("this.videoList视频列表:", this.videoList);
					setTimeout(() => {
						// 延时结束，执行的操作
						this.refreshStatus = false
					}, 2000);
					this.isRefresh = false
				}).catch(err => {
					setTimeout(() => {
						// 延时结束，执行的操作
						this.refreshStatus = false
					}, 2000);
					this.isRefresh = false
				})
			},
			openVideoDetail(lItems) {
				PlayerManager.navigateToPlayer({
					// srcAppid: 'wxeb772bb1406b39ae',
					// dramaId: '100071',
					srcAppid: uni.getStorageSync('srcAppid'),
					dramaId: lItems.dramaId,
					extParam: encodeURIComponent('a=b&c=d'), // 分享会携带的参数，可自定义
				})
			},
			opShow() {
				this.show = true
			},
			close() {
				this.show = false
			},
			// 	收藏
			handleCollect(id, collect, index) {
				if (collect == 0) {
					const obj = {
						vid: id,
						type: 'favorite'
					}
					this.$request('video.addRecord', obj, false).then(res => {
						if (res.code === 1) {}
					})
				} else {
					const obj = {
						ids: id,
						type: 'favorite'
					}
					this.$request('video.deleteRecord', obj, false).then(res => {
						if (res.code === 1) {}
					})
				}
			},
			// 下拉刷新
			refreshHandle() {
				this.refreshStatus = true
				if (!this.isRefresh) {
					this.isRefresh = true
					this.getVideoList()
				}
			},
			// 滚动监听
			scrollHandle(e) {
				if (this.contentCurrent == 0) {
					this.isTabsFixed = e.detail.scrollTop > 200 ? true : false
				}
			},
			// 触底滚动
			bottomHandle() {
				// this.contentList[this.contentCurrent].page++
				this.getVideoList()
			},
			isSelected(tabItem) {
				// return this.tabsActive.id === tabItem.id;
				return this.tabsActive[tabItem.id] !== undefined;
			},
			// 切换tabs
			changeTabs(tabItem) {
				const keys = Object.keys(this.tabsActive);
				console.log("keys:", keys);
				if (this.tabsActive[tabItem.id]) {
					// 如果该 tab 已经被选中，就取消选中
					delete this.tabsActive[tabItem.id];
				} else {
					// 如果该 tab 未被选中，就选中
					this.tabsActive[tabItem.id] = tabItem;

				}
				// 更新 this.videoQuery.dramaClassify
				this.videoQuery.dramaClassify = Object.keys(this.tabsActive).join(',');
				// 获取视频列表
				this.getVideoList();
			},
			// 频道筛选
			choiceTabs(item, tabItem) {
				if (this.selectedTabId === tabItem.id) {
					this.selectedTabId = null; // 取消选中
					this.videoQuery.dramaChannel = null
				} else {
					this.selectedTabId = tabItem.id; // 更新选中的选项 ID
					this.videoQuery.dramaChannel = tabItem.id;
				}
			},
			classTabs(item) {
				this.classification[item].type = true
			},
			// 重置筛选条件
			reset() {
				this.selectedTabId = ""
				this.episodeId = ""
				this.tabsActive = {};
				this.videoQuery.dramaClassify = '';
				// console.log("已取消所有选中状态");
				this.getVideoList(); // 获取视频列表
			},
			confirm() {
				this.show = false
				console.log(this.videoQuery, "this.videoQuery")
				this.getVideoList()
			},

		}
	}
</script>

<style lang="scss" scoped>
	.page-bgc {
		background: linear-gradient(to bottom, rgba(235, 229, 255, 0.9), rgba(170, 238, 221, 0.0));
		/* 渐变的颜色及透明度 */
		height: 200rpx;
		/* 让背景填满整个视口高度 */
		width: 100%;
		/* 让背景填满整个视口宽度 */
		box-sizing: border-box;
		position: absolute;
		/* 使用绝对定位 */
		top: 0;
		/* 定位在页面的顶部 */
		left: 0;
		/* 定位在页面的左侧 */
		z-index: -1;
		/* 确保背景色在其他内容之下 */
	}

	.backls {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .4);
	}

	.page_content {
		z-index: 999;
		position: relative;
		overflow: hidden;

		.tabs {
			padding-bottom: 30rpx;
			display: flex;
			align-items: center;
			position: relative;

			.itemList {
				display: flex;
				align-items: center;
				width: 92%;
				overflow-y: auto;

				.items {
					color: #000;
					padding: 14rpx 26rpx;
					border-radius: 12rpx;
					font-size: 32rpx;
					// font-weight: 700;
					background-color: $uni-color-bgc;
					margin-right: 16rpx;
					white-space: nowrap;

					&.active {
						background-color: $uni-color-tab-act;
						color: $uni-color-error;
					}
				}
			}

			.icon {
				width: 8%;
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}




			&.top {
				height: 0;
				padding: 0 40rpx;
				overflow: hidden;
				transition: all 0.2s linear;

				&.show {
					height: 94rpx;
					padding: 20rpx 40rpx;
				}
			}


		}


		.head_content {
			.navbar {
				margin-top: 88rpx;
				margin-bottom: 20rpx;
				padding: 16rpx 20rpx 16rpx 20rpx;
				font-size: 44rpx;
				font-weight: bold;
			}

			.tabs_box {
				padding: 0 20rpx 10rpx;
				position: relative;

				.search {
					position: absolute;
					top: 50%;
					right: 0;
					transform: translate(100%, -55%);
				}
			}
		}

		.main_content {
			overflow: hidden;

			.content_box {
				padding: 0 20rpx 60rpx 20rpx;
				height: 100%;

				.list {
					display: grid;
					grid-template-columns: 1fr 1fr 1fr;
					grid-gap: 8px;
					margin-top: 20rpx;
					padding-bottom: 168rpx;

					.item {
						width: 100%;

						&.item1 {

							&:nth-child(10n),
							&:nth-child(10n-3),
							&:nth-child(10n-6) {
								margin-right: 0;
							}
						}

						&.item2 {
							&:nth-child(3n) {
								margin-right: 0;
							}
						}

						.img {
							width: 100%;
							height: 282rpx;
							border-radius: 16rpx;
							overflow: hidden;
							position: relative;

							.image {
								width: 100%;
								height: 100%;
							}

							.count {
								position: absolute;
								left: 24rpx;
								bottom: 24rpx;
								color: #fff;
								display: flex;
								align-items: center;
								font-size: 28rpx;
							}
						}

						.info {
							margin-top: 16rpx;

							.title {
								font-size: 32rpx;
								color: #000;
							}

							.text {
								font-size: 28rpx;
								color: #858585;
								margin-top: 4rpx;
							}
						}
					}
				}

				.nodata {
					padding: 15vh 0;
				}
			}
		}
	}

	.opBox {
		position: relative;
		button: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding: 32rpx 32rpx 164rpx 32rpx;
		border-radius: 18rpx 18rpx 0 0;
		z-index: 9;

		.opTitle {
			position: relative;

			.text {
				text-align: center;
				font-weight: bold;
			}

			.close {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				right: 0;
			}
		}

		.opContent {
			.boxT {
				margin-bottom: 24rpx;

				.t-title {
					margin-bottom: 16rpx;
					color: #4f4f4f;
					font-weight: bold;
				}

				.t-content {
					display: grid;
					grid-template-columns: 1fr 1fr 1fr;
					grid-gap: 16px;

					.t-item {
						background-color: $uni-color-bgc;
						display: flex;
						justify-content: center;
						align-items: center;
						height: 100rpx;
						border-radius: 16rpx;
						font-weight: bold;
					}

					.active {
						background-color: $uni-color-tab-act;
						color: $uni-color-error;
					}
				}
			}

			.boxC {
				margin-bottom: 24rpx;

				.c-title {
					margin-bottom: 16rpx;
					color: #4f4f4f;
					font-weight: bold;
				}

				.c-content {
					display: grid;
					grid-template-columns: 1fr 1fr 1fr;
					grid-gap: 16px;

					.c-item {
						background-color: $uni-color-bgc;
						display: flex;
						justify-content: center;
						align-items: center;
						height: 100rpx;
						border-radius: 16rpx;
						font-weight: bold;
					}

					.active {
						background-color: $uni-color-tab-act;
						color: $uni-color-error;
					}
				}
			}

			.boxB {
				margin-bottom: 64rpx;

				.b-title {
					margin-bottom: 16rpx;
					color: #4f4f4f;
					font-weight: bold;
				}

				.b-content {
					display: grid;
					grid-template-columns: 1fr 1fr 1fr;
					grid-gap: 16px;

					.b-item {
						background-color: $uni-color-bgc;
						display: flex;
						justify-content: center;
						align-items: center;
						height: 100rpx;
						border-radius: 16rpx;
						font-weight: bold;
					}

					.active {
						background-color: $uni-color-tab-act;
						color: $uni-color-error;
					}
				}
			}

			.btnBox {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.reset {
					border-radius: 50rpx;
					border: 2rpx solid #000;
					height: 100rpx;
					width: 328rpx;
					text-align: center;
					line-height: 96rpx;
					font-size: 36rpx;
					font-weight: bold;
				}

				.confirm {
					border-radius: 50rpx;
					background-color: #19b9cc;
					color: #fff;
					height: 100rpx;
					width: 328rpx;
					text-align: center;
					line-height: 100rpx;
					font-size: 36rpx;
					font-weight: bold;
				}
			}
		}
	}
</style>